// author fucaihe@pryun.com.cn
// create time 2018-01-13 23:02:56
// 字符串工具

package kit

import (
	"bytes"
	"compress/zlib"
	"encoding/binary"
	"encoding/hex"
	"io"
	"reflect"
	"regexp"
	"strconv"
	"strings"

	"github.com/pquerna/ffjson/ffjson"
)

// IsBlank s是否为空
func IsBlank(s string) bool {
	return strings.TrimSpace(s) == ""
}

// SubString 截取字符串,支持中文
func SubString(s string, start, end int) string {
	arr := []rune(s)
	if end > len(arr) {
		end = len(arr)
	}
	return string(arr[start:end])
}

// HTMLToPlainText 字符串HTML变成Text
func HTMLToPlainText(html string) string {
	re, _ := regexp.Compile("(?s)<[^>]*>(\\s*<[^>]*>)*")
	nhtml := re.ReplaceAllString(html, "")
	notmp := strings.Replace(nhtml, " ", "", -1)
	turCtx := strings.Replace(notmp, "\n", "", -1)
	return turCtx
}

// WordCount 字符串字数
func WordCount(s string) int {
	return len([]rune(s))
}

// TrimSpace 去除前后空格
func TrimSpace(s string) string {
	return strings.TrimSpace(s)
}

// JSONStrToMap 字符串转MAP
func JSONStrToMap(body []byte) map[string]string {
	rst := make(map[string]string)
	ffjson.Unmarshal(body, &rst)
	return rst
}

// CountToInt64 统计类型的数据转int64
func CountToInt64(body []byte) (int64, error) {
	countStr := strings.TrimSpace(string(body))
	if strings.Contains(countStr, "k") {
		countStr = strings.Replace(countStr, "k", "000", -1)
	}
	if strings.Contains(countStr, "w") {
		countStr = strings.Replace(countStr, "w", "0000", -1)
	}
	if strings.Contains(countStr, "+") {
		countStr = strings.Replace(countStr, "+", "", -1)
	}
	return strconv.ParseInt(countStr, 10, 64)
}

// UnicodeToStr Unicode转字符串
func UnicodeToStr(form string) (to string, err error) {
	bs, err := hex.DecodeString(strings.Replace(form, `\u`, ``, -1))
	if err != nil {
		return
	}
	for i, bl, br, r := 0, len(bs), bytes.NewReader(bs), uint16(0); i < bl; i += 2 {
		binary.Read(br, binary.BigEndian, &r)
		to += string(r)
	}
	return
}

// CompressData 数据压缩

// ZlibCompress zlib数据压缩
func ZlibCompress(input []byte) ([]byte, error) {
	var in bytes.Buffer
	w, err := zlib.NewWriterLevel(&in, zlib.BestCompression)
	if err != nil {
		return nil, err
	}
	w.Write(input)
	w.Close()
	return in.Bytes(), nil
}

// ZlibUnCompress zlib数据解压缩
func ZlibUnCompress(compressBody []byte) ([]byte, error) {
	b := bytes.NewReader(compressBody)
	var out bytes.Buffer
	r, err := zlib.NewReader(b)
	if err != nil {
		return nil, err
	}
	io.Copy(&out, r)
	return out.Bytes(), nil
}

// ContentHasImage 字符串是否包含图片
func ContentHasImage(content string) string {
	var st string
	if strings.Contains(content, "<img") {
		st = "是"
	} else {
		st = "否"
	}
	return st
}

// GetNumber 从字符串中获取数字
func GetNumber(str string) int64 {
	valid := regexp.MustCompile(`[\d]+`) // 非贪婪模式,才能分开多个
	numberStr := ""
	for _, key := range valid.FindAllString(str, -1) {
		numberStr = numberStr + key
	}
	number, _ := strconv.ParseInt(numberStr, 10, 64)
	return number
}

// NumberFormatter 数字格式化,统计数值类型转换(阅读量,点赞量,回复量等)
// 1k=1000
// 1w=10000
// 2w3k=23000
// 2.3k=2300
// 2.5w=2500
// 10w1.256k=101256
func NumberFormatter(countStr string) int64 {
	countStr = strings.ToLower(countStr)

	valid := regexp.MustCompile(`([0-9]+w)|([0-9]*\.?[0-9]+k)`) // 贪婪模式,保证到最后一个'}'
	var count int64
	if valid.MatchString(countStr) {
		for _, txt := range valid.FindAllString(countStr, -1) {
			var tempCount int64
			if strings.HasSuffix(txt, "w") {
				tempCount, _ = strconv.ParseInt(strings.Replace(txt, "w", "", -1), 10, 64)
				tempCount = tempCount * 10000
			} else if strings.HasSuffix(txt, "k") {
				fltCount, _ := strconv.ParseFloat(strings.Replace(txt, "k", "", -1), 64)
				tempCount = int64(fltCount * 1000)
			}
			count = count + tempCount
		}
	} else {
		count = GetNumber(countStr)
	}
	return count
}

// GetCurrentSourceIndex 获取当前要录入的源数据索引名称
func GetCurrentSourceIndex() string {
	return "wenxinnews_" + GetCurrentDateStr("20060102")
}

// // GetWebSiteLinkForMedia 获取媒体判断的websitelink
// func GetWebSiteLinkForMedia(s string) string {
// 	arr := strings.Split(s, ".")
// 	if len(arr) >= 2 {
// 		s = fmt.Sprintf("%s.%s", arr[0], arr[1])
// 	}
// 	return s
// }

// GetWebSiteLinkForMedia 获取媒体判断的websitelink
func GetWebSiteLinkForMedia(s string) string {
	if strings.HasPrefix(s, "http") {
		arr := strings.Split(s, "//")
		s = arr[1]
		s = arr[0] + "//" + strings.Split(s, "/")[0]
	} else if strings.HasPrefix(s, "//") {
		arr := strings.Split(s, "//")
		s = arr[1]
		s = "http://" + strings.Split(s, "/")[0]
	} else {
		arr := strings.Split(s, "/")
		s = "http://" + arr[0]
	}

	return s
}

// WordCountHTML 统计HTML内容字数
func WordCountHTML(s string) int {
	re, _ := regexp.Compile("(?s)<[^>]*>(\\s*<[^>]*>)*")
	nhtml := re.ReplaceAllString(s, "")
	nhtml = strings.Replace(nhtml, " ", "", -1)
	nhtml = strings.Replace(nhtml, "\n", "", -1)
	return WordCount(nhtml)
}

// MultiplyAB 求乘, 200*200
func MultiplyAB(mulStr string) float64 {
	arr := strings.Split(mulStr, "*")
	a, _ := strconv.ParseFloat(arr[0], 64)
	b, _ := strconv.ParseFloat(arr[1], 64)
	return a * b
}

// IsCopyright 是否原创
func IsCopyright(input, s string) bool {
	return strings.Contains(s, input)
}

//IsEmpty 所有类型 是否为空
func IsEmpty(a interface{}) bool {
	v := reflect.ValueOf(a)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	return v.Interface() == reflect.Zero(v.Type()).Interface()
}
